import { ref, shallowRef } from 'vue'

import { getMBTICategory } from './api'
import { catchFn } from '@/libs/common'
import { createQuiz } from '../../api'
import { clearCache, startTest, startTestWithHistory } from '../detail/data'

const title = ref('')
const list = shallowRef<
  {
    id: number
    key: string
    value: string
  }[]
>([])

export { title, list }

/**
 * 更新MBTI测试分类
 */
const init = () =>
  catchFn(async () => {
    const { data } = await getMBTICategory()

    title.value = data.title
    list.value = data.list
  })

/**
 * 开始测试
 * @param code 测试类型代码
 */
const select = (code: string) => {
  // 检测历史缓存
  const last_test = uni.getStorageSync('mbti_test')

  if (last_test) {
    uni.showModal({
      title: '提示',
      content: '您未完成上一次测试，是否继续？',
      confirmText: '继续',
      cancelText: '新测试',
      success(res) {
        if (res.confirm) startTestWithHistory(last_test)
        else if (res.cancel) {
          clearCache()
          start(code)
        }
      },
    })
  } else start(code)
}

/**
 * 开始测试
 * @param code 测试类型代码
 */
const start = (code: string) =>
  catchFn(async () => {
    const { data } = await createQuiz(code)

    startTest(data, data.firstQuestion.id)
  })

export { init, select }
